<?php

namespace App\Common\SDK\Domain;

use App\Common\Utils\Rsa;
use Illuminate\Support\Facades\Log;

class ZhiLing extends Base
{
    protected $appKey = '';

    protected function requestAfter($response)
    {
        return json_decode($response, true);
    }

    private function sign($params)
    {
        ksort($params);

        $pair = [];
        foreach ($params as $k => $v) {
            $pair[] = $k . '=' . $v;
        }
        $str = implode('&', $pair);

        return strtolower(md5($str . '&key=' . env('ZHI_LING_APP_SECRET')));
    }

    protected function assembleParams($params)
    {
        $rsaUtil = new Rsa(resource_path('sms/private.pem'), resource_path('sms/public.pem'));
        $data = $rsaUtil->publicEncrypt(json_encode($params));

        return [
            'app_key' => $this->appKey,
            'version' => 'v1',
            'data' => $data,
            'sign' => $this->sign($params),
        ];
    }

    public function sms($params = [])
    {
        if (app()->environment(['local'])) {
            return true;
        }

        $this->appKey = env('ZHI_LING_SMS_APP_KEY');

        return $this->request(self::METHOD_POST, '', $params);
    }
}
